package com.ymk.cmd;

import com.alibaba.fastjson.JSON;
import com.ymk.base.cmd.ACmd;
import com.ymk.base.cmd.CmdSign;
import com.ymk.base.exception.MallException;
import com.ymk.base.utlis.ParamsBuilder;
import com.ymk.bo.pay.PayPaymentBO;
import com.ymk.core.code.cmd.PayPaymentCmdCode;
import com.ymk.mq.MessageSender;
import com.ymk.service.IPayPaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Objects;

@Controller
public class PayNotifyCmd extends ACmd {
    private final static Logger logger = LoggerFactory.getLogger(PayNotifyCmd.class);

    @Override
    public CmdSign execute(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        PayPaymentBO payPaymentBO = super.getData(sign, PayPaymentBO.class);
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("payNo",payPaymentBO.getPayNo());

        PayPaymentBO dbPayPaymentBO = this.payPaymentService.get(paramsBuilder.build());
        if (Objects.isNull(dbPayPaymentBO)){
            logger.error("支付回调订单不存在："+ JSON.toJSONString(payPaymentBO));
            throw new MallException("订单不存在");
        }
        if (dbPayPaymentBO.getAmount().compareTo(payPaymentBO.getAmount().divide(new BigDecimal("100"),BigDecimal.ROUND_CEILING)) != 0){
            logger.error("支付金额错误："+ JSON.toJSONString(payPaymentBO));
            throw new MallException("支付金额错误");
        }

        CmdSign build = CmdSign.Builder.newBuild(sign)
                .setSource(dbPayPaymentBO)
                .setCmdCode(PayPaymentCmdCode.PAY_PAYMENT_SYNC)
                .build();
        this.scheduler.schedule(request,build);
        return respSign;
    }

    @Override
    public String getCmdCode() {
        return PayPaymentCmdCode.PAY_PAYMENT_NOTIFY;
    }

    @Autowired
    protected MessageSender messageSender;
    @Autowired
    private IPayPaymentService payPaymentService;
}
